#include"mystdio.h"

#include <sys/types.h>                                      
#include<sys/stat.h>
#include<fcntl.h>
#include<cstring>
#include<cstdlib>
#include<unistd.h>

MyFile* BuyFile(int flag,int fd)
{
  MyFile* f=(MyFile*)malloc(sizeof(MyFile));
  if(f==nullptr) return nullptr;
  f->flag=flag;
  f->flush_method=LINE_FLUSH;
  f->fileno=fd;
  memset(f->outbuffer,0,sizeof(f->outbuffer));
  f->bufferlen=0;
  return f;
}

MyFile* MyFopen(const char* path,const char* mode)
{
  int flag=0;
  int fd=-1;
  if(strcmp(mode,"w")==0)
  {
    flag=O_WRONLY|O_CREAT|O_TRUNC;
    fd=open(path,flag,0666);
  }
 else  if(strcmp(mode,"a")==0)
  {
    flag=O_CREAT|O_APPEND|O_WRONLY;
    fd=open(path,flag,0666);
  }
  else if(strcmp(mode,"r")==0)
  {
    flag=O_RDWR;
    fd=open(path,flag);
  }
  if(fd==-1) return nullptr;

  return BuyFile(flag,fd);

}
void MyFclose(MyFile* file)
{
  if(file->fileno<0) return ;
  MyFflush(file);
 close(file->fileno);
 free(file);
}
int MyWrite(MyFile* file,void* str,int len)
{
  memcpy(file->outbuffer+file->bufferlen,str,len);
  file->bufferlen+=len;

  if(file->flush_method==LINE_FLUSH  &&
      file->outbuffer[file->bufferlen-1]=='\n' )
MyFflush(file);
  return 0;
}
void MyFflush(MyFile* file)
{
  if(file->bufferlen<=0) return;
  int n=write(file->fileno,file->outbuffer,file->bufferlen);
  (void)n;
  fsync(file->fileno);
  file->bufferlen=0;
}


